package com.hzqy.service.wchat;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.hzqy.web.vo.wchat.LoginMessage.ReceiveMessage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.MessageUtil;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.WChatUtil;
import com.hzqy.persistence.dao.wchat.WchatWXDao;
import com.hzqy.web.vo.WxAccessTokenVo;
import com.hzqy.web.vo.wchat.TextMessage;


@Service
public class WechatWXService {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	WchatWXDao wchatWXDao;

	public String connect(String signature, String timestamp, String nonce, String echostr) throws IOException{
		String result = "";
		String Token = SystemConfigUtils.getSysConfig("wx_token");
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (WChatUtil.checkSignature(Token, signature, timestamp, nonce)) {
			LOG.info("微信接入验证成功，返回原始Token。");
			result = echostr;
		} else {
			LOG.error("微信接入失败，验证signature失败！");
		}
		return result;
	}

	public Map<String, String> access_token_I() {
		String appid = SystemConfigUtils.getSysConfig("wx_appid");
		String secret = SystemConfigUtils.getSysConfig("wx_secret");
		String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=%s&appid=%s&secret=%s", "client_credential", appid, secret);
		Map<String, String> resultMap = WChatUtil.get(url, null);
		return resultMap;
	}

	public Map<String, String> wx_service_ips_I() {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=%s", WxAccessTokenVo.getAccessToken(true));
		Map<String, String> resultMap = WChatUtil.get(url, null);
		return resultMap;
	}

	public Map<String, String> jsapi_ticket() {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=%s", WxAccessTokenVo.getAccessToken(true), "jsapi");
		Map<String, String> resultMap = WChatUtil.get(url, null);
		return resultMap;
	}

	public Map<String, String> auth_access_token(String wx_appid, String wx_secret, String code) {
		String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=%s", wx_appid, wx_secret, code, "authorization_code");
		Map<String, String> resultMap = WChatUtil.get(url, null);
		return resultMap;
	}

	public Map<String, Object> jsapi_config(String currentUrl) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("jsapi_ticket", WxAccessTokenVo.getJsAccessToken(true));
		resultMap.put("timestamp", System.currentTimeMillis());
		resultMap.put("noncestr", WChatUtil.randomString(16));
		resultMap.put("url", currentUrl.substring(0, currentUrl.indexOf("#") >= 0 ? currentUrl.indexOf("#") : currentUrl.length()));
		resultMap.put("signature", WChatUtil.JsapiSignature(resultMap));
		WxAccessTokenVo wxAccessTokenVo = WxAccessTokenVo.getAccessTokenVo(WxAccessTokenVo.application_access_token_key);

		resultMap.put("wx_token", wxAccessTokenVo.getWx_token());
		resultMap.put("wx_appid", wxAccessTokenVo.getWx_appid());
		resultMap.put("wx_secret", wxAccessTokenVo.getWx_secret());
		return resultMap;
	}

	public Map<String, String> create_menu() {
		JSONObject json = new JSONObject();

		JSONArray buttonArr = new JSONArray();
		json.put("button", buttonArr);
		SecureRandom random = new SecureRandom();
		try {
			String[] urlArr = {
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6b080c108ec90421&redirect_uri=" + URLEncoder.encode("http://www.kdwxgz.cn:5556/gd_hqjc_admin/hotel/wchat/protal.jsp", "UTF-8") + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect",
					"http://www.kdwxgz.cn:5556/gd_hqjc_admin/hotel/wchat/accountBinding.jsp",
					"http://www.kdwxgz.cn:5556/gd_hqjc_admin/hotel/wchat/portal.jsp"
			};

			for(int i = 0; i < 3; i ++) {
				JSONObject btn = new JSONObject();
				btn.put("type", "view");
				btn.put("name", "测" + random.nextDouble() * 10 + "-" + i);
				btn.put("url", urlArr[i]);
				buttonArr.add(btn);
			}

			JSONObject matchrule = new JSONObject();
			json.put("matchrule", matchrule);

			matchrule.put("language", "zh_CN");

		} catch (Exception e) {
			e.printStackTrace();
		}

		LOG.debug("参数：" + json.toJSONString());
		String url = String.format("https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=%s", WxAccessTokenVo.getAccessToken(true));
		Map<String, String> resultMap = WChatUtil.post(url, json.toJSONString());
		return resultMap;
	}

	/*	{ "access_token":"ACCESS_TOKEN",
             "expires_in":7200,
             "refresh_token":"REFRESH_TOKEN",
             "openid":"OPENID",
             "scope":"SCOPE" } */
	public Map<String, String> openid_bycode(String code, String state) {
		WxAccessTokenVo wxAccessTokenVo = WxAccessTokenVo.getAccessTokenVo(WxAccessTokenVo.application_access_token_key);
		Map<String, String> resultMap = auth_access_token(wxAccessTokenVo.getWx_appid(), wxAccessTokenVo.getWx_secret(), code);
		Map<String, String> returnMap = new HashMap<String, String>();
		returnMap.put("openid", "");
		LOG.debug("auth_callback_scope_base 获取access_token返回结果: " + resultMap);
		if("1".equals(resultMap.get("success"))) {
			String result = resultMap.get("msg");
			JSONObject json = JSONObject.parseObject(result);
			if(StringUtils.isNotEmpty(json.getString("openid"))) {
				returnMap.put("openid", json.getString("openid"));
			}
		}

		return returnMap;
	}

	public Map<String, String> user_info_by_openid(String openid) {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=%s", WxAccessTokenVo.getAccessToken(true), openid, "zh_CN");
		Map<String, String> resultMap = WChatUtil.get(url, null);
		return resultMap;
	}

	public Map<String, Object> get_media(String media_id, String destDir) {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", WxAccessTokenVo.getAccessToken(true), media_id);
		String dest = destDir;
		if(!(destDir.endsWith("/") || destDir.endsWith("\\"))) {
			dest += File.separator;
		}
		dest += media_id + ".jpg";
		Map<String, Object> resultMap = WChatUtil.getFile(url, dest);
		return resultMap;
	}

	public Map<String, Object> get_ticket(JSONObject json,int scene_id) throws UnsupportedEncodingException {
		LOG.debug("2");
		String url = String.format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s", WxAccessTokenVo.getAccessToken(true));
		Map<String, String> resultMap = WChatUtil.post(url,json.toJSONString());
		String ticket = JSONObject.parseObject(resultMap.get("msg")).get("ticket").toString();
		LOG.debug(ticket);
		String url1 = String.format("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s",URLDecoder.decode(ticket,"utf-8"));
		Map<String, Object> resultMap1 = WChatUtil.getFile(url1,"/home/test/tomcat-weixin/webapps/admin/PIC/imgs/upload/content/wx-ewm/"+scene_id+".jpg");
		return resultMap1;
	}

	/**
	 * 处理微信发来的请求 未完成
	 *
	 * @param request
	 * @return
	 */
	public String weixinPost(HttpServletRequest request) {
		String respMessage = null;
		try {
			Map<String, String> requestMap = MessageUtil.xmlToMap(request);// xml请求解析
			String fromUserName = requestMap.get("FromUserName");// 发送方帐号（open_id）
			String toUserName = requestMap.get("ToUserName");// 公众帐号
			String msgType = requestMap.get("MsgType");// 消息类型
			String content = requestMap.get("Content");// 消息内容

			LOG.debug("FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);

			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { // 文本消息
				// 这里根据关键字执行相应的逻辑，只有你想不到的，没有做不到的
				if (content.equals("xxx")) {}
				// 自动回复
				TextMessage text = new TextMessage();
				text.setContent("the text is" + content);
				text.setToUserName(fromUserName);
				text.setFromUserName(toUserName);
				text.setCreateTime(new Date().getTime() + "");
				text.setMsgType(msgType);
				respMessage = MessageUtil.textMessageToXml(text);
			} else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				/*String recvMessage = requestMap.get("Recognition");
				LOG.debug("收到语音消息:recvMessage="+recvMessage);
				WchatTvUserVo wchatTvUserVo = wchatTvUserWeixinDao.selectUserInfo(fromUserName);
				if(wchatTvUserVo!=null) {
					String serverId = wchatTvUserVo.getF_wtut_serverid();
					String message = null;
					try {
						message = parseWXMessage(serverId,recvMessage,fromUserName);
					} catch(Exception e) {
						LOG.error("解析命令字异常：",e);
					}
					if(message == null) {
						recvMessage = "您发送的语音无法识别机顶盒操作指令，语音为："+recvMessage;
					} else {
						LOG.debug("语音消息发向机顶盒命令字="+message);
						WsSessionVo stbSession = CommonsMessage.getStbSessionFromCache(serverId);
						if(stbSession == null || stbSession.getSession()==null) {
							recvMessage = "您微信绑定的机顶盒未正常登录，请检查！";
						} else {
							if(message.indexOf("|")!=-1) { //向机顶盒发起命令
								CommonsMessage.send(stbSession.getSession(), message);
								recvMessage = "您发送的语音为："+recvMessage;
							} else { //向微信回复
								recvMessage = message;
							}
						}
					}
					respMessage = getReturnWsMessage(fromUserName,toUserName,MessageUtil.RESP_MESSAGE_TYPE_TEXT,recvMessage);
				} else { //用户未绑定机顶盒
					recvMessage = "您的微信号未绑定您的机顶盒。";
					respMessage = getReturnWsMessage(fromUserName,toUserName,MessageUtil.RESP_MESSAGE_TYPE_TEXT,recvMessage);
				}*/
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				String eventType = requestMap.get("Event");// 事件类型
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
					String eventKey = requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					LOG.error("event未知自定义菜单KEY值,eventKey="+eventKey);
				} else {
					LOG.error("event未知事件类型,eventType="+eventType);
				}
			} else {
				LOG.error("msgType未知消息类型,msgType="+msgType);
			}
		} catch (Exception e) {
			LOG.error("error......", e);
		}
		return respMessage;
	}
	public Integer insertRSMS(ReceiveMessage vo){
		Integer flag=wchatWXDao.insertRSMS(vo);
		return flag;
	}
	public ReceiveMessage selectRSMS(ReceiveMessage vo){
		return wchatWXDao.selectRSMS(vo);

	}
	public Integer updateRSMS(ReceiveMessage vo){
		Integer flag=wchatWXDao.updateRSMS(vo);
		return flag;
	}

	public Integer selectRSMSCount(ReceiveMessage vo){
		Integer flag=wchatWXDao.selectRSMSCount(vo);
		return flag;
	}

}